const fs = require('fs')
const path = require('path')
const play = require('./play')
// const marked = require('marked');
// var svg_to_png = require('svg-to-png');
// 加载游戏进本地内存
let gameList = getGameList()
// 获取游戏列表
function getGameList() {
    let dir = fs.readdirSync(path.resolve(__dirname, `./gameList`))
    var obj = {}
    dir.forEach(item => {
        var jsonData = JSON.parse(fs.readFileSync(path.resolve(__dirname, `./gameList/${item}`)).toString())
        let title = jsonData.title
        obj[title] = jsonData
    })
    return obj
}


// 开始游戏
function startGame(gameName, name, qunName) {
    return new Promise(resFn => {
        // 判断有没有存档  没有存档就创建存档
        // 获取目录下面的对应存档的文件
        var save;
        try {
            save = JSON.parse(fs.readFileSync(path.resolve(__dirname, `./save/${name}.json`)).toString())

            if (typeof save[gameName] == 'undefined') {

                save[gameName] = {
                    player: `来自${qunName}的小伙伴`,
                    chapter: "1.1",
                    variables: {},
                    inputs: []
                }
                fs.writeFileSync(path.resolve(__dirname, `./save/${name}.json`), JSON.stringify(save))
            }

        } catch {
            let saveTemp = {
                [gameName]: {
                    player: `来自${qunName}的小伙伴`,
                    chapter: "1.1",
                    variables: {},
                    inputs: []
                }

            }
            fs.writeFileSync(path.resolve(__dirname, `./save/${name}.json`), JSON.stringify(saveTemp))
            save = saveTemp
        }
        // 继续游戏
        var scene = play("", save[gameName], gameList[gameName])
        // 展示剧情
        resFn(scene.output)
    })
}
// 游戏中
function onlienGame(text, name, gameName) {
    return new Promise(resFn => {
        var save;
        // 获取修改存档
        try {
            // 获取存档
            save = JSON.parse(fs.readFileSync(path.resolve(__dirname, `./save/${name}.json`)).toString())
            // 修改存档
            save[gameName].inputs.push(text)
            if (text == '重置' || text == '重新开始') {
                save[gameName] = {
                    player: `来自${gameName}的小伙伴`,
                    chapter: "1.1",
                    variables: {},
                    inputs: []
                }
            }
            // 进行游戏
            scene = play(text, save[gameName], gameList[gameName])
            // 存档
            save[gameName].chapter = scene.chapter
            save[gameName].variables = scene.variables
            fs.writeFileSync(path.resolve(__dirname, `./save/${name}.json`), JSON.stringify(save))
        } catch {
            resFn('发生错误')
        }
        // 展示剧情
        resFn(scene.output)
    })
}





module.exports = {
    gameList,
    startGame,
    onlienGame
}